/*
 * ArithmeticUnit.cpp
 *
 *  Created on: 2012-5-20
 *      Author: WuyaMony
 */
#include"ArithmeticUnit.h"
namespace my {

ArithmeticUnit::ArithmeticUnit(deque<int>&data) :
		_data(data), taskNum(0) {
	t.isCalc = false;
	for (int i = 1; i < 5; ++i) {
		_calc.push_back(t);
	}
}
void ArithmeticUnit::addTask(int a, int b, int (*func)(int, int)) {
	taskNum++;
	t.isCalc = true;
	t.a = a;
	t.b = b;
	t.func = func;
//	cout << "\tadd task" << t.a << "," << t.b << endl;
}

void ArithmeticUnit::Tick() {
	Task tmp = _calc.front();
	_calc.pop_front();
	Task tmp2 = _calc.front();
	_calc.pop_front();
	bool ismul, isadd;
	ismul = tmp.isCalc;
	isadd = tmp2.isCalc;
	if (ismul) {
		_data.push_back(tmp.func(tmp.a, tmp.b));
		taskNum--;
	}
	if (isadd) {
		if (ismul) {
			_calc.front() = tmp2;
		} else {
			_data.push_back(tmp2.func(tmp2.a, tmp2.b));
			taskNum--;
		}
	}

	if (_calc.back().isCalc && _calc.back().func == mul) {
		_calc.push_front(_calc.back());
		_calc.back().isCalc = false;
	} else {
		Task tmp3;
		tmp3.isCalc = false;
		_calc.push_front(tmp3);
	}

	_calc.push_back(t);
	t.isCalc = false;
}
}
